<template>
  <el-container class="layout-container">
    <el-aside :width="isCollapse ? '64px' : '200px'" class="aside-container">
      <div class="logo-container">
        <span class="logo-text" v-if="!isCollapse">后台管理系统</span>
        <el-icon v-else><Platform /></el-icon>
      </div>
      <el-menu
        :default-active="activeMenu"
        class="el-menu-vertical"
        :collapse="isCollapse"
        :background-color="currentTheme.menuBg"
        :text-color="currentTheme.menuText"
        :active-text-color="currentTheme.menuActiveText"
        unique-opened
        router
      >
        <template v-for="route in menuRoutes" :key="route.path">
          <!-- 单层菜单 -->
          <el-menu-item
            v-if="!route.children || route.children.length === 1"
            :index="route.path + (route.children ? '/' + route.children[0].path : '')"
          >
            <el-icon v-if="route.meta?.icon">
              <component :is="route.meta.icon" />
            </el-icon>
            <template #title>{{ route.meta?.title }}</template>
          </el-menu-item>

          <!-- 多层菜单 -->
          <el-sub-menu
            v-else
            :index="route.path"
          >
            <template #title>
              <el-icon v-if="route.meta?.icon">
                <component :is="route.meta.icon" />
              </el-icon>
              <span>{{ route.meta?.title }}</span>
            </template>

            <el-menu-item
              v-for="child in route.children"
              :key="route.path + '/' + child.path"
              :index="route.path + '/' + child.path"
            >
              <el-icon v-if="child.meta?.icon">
                <component :is="child.meta.icon" />
              </el-icon>
              <template #title>{{ child.meta?.title }}</template>
            </el-menu-item>
          </el-sub-menu>
        </template>
      </el-menu>
    </el-aside>

    <el-container>
      <el-header>
        <div class="header-left">
          <el-button type="primary" link @click="toggleCollapse">
            <el-icon :size="20">
              <component :is="isCollapse ? 'Expand' : 'Fold'" />
            </el-icon>
          </el-button>
        </div>
        <div class="header-right">
          <!-- 主题切换 -->
          <el-dropdown @command="handleThemeChange" class="theme-picker" :trigger="['click']">
            <el-button type="primary" link>
              <el-icon><Brush /></el-icon>
              <span>主题色</span>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  v-for="theme in themeColors"
                  :key="theme.value"
                  :command="theme"
                >
                  <div class="theme-item">
                    <div
                      class="theme-color"
                      :style="{ backgroundColor: theme.value }"
                    ></div>
                    <span>{{ theme.name }}</span>
                  </div>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>

          <el-dropdown @command="handleCommand" :trigger="['click']">
            <div class="user-info">
              <el-avatar
                :size="32"
                :src="userStore.userInfo.avatar"
                class="user-avatar"
              >
                {{ userStore.userInfo.nickname?.charAt(0)?.toUpperCase() || 'A' }}
              </el-avatar>
              <span class="username">{{ userStore.userInfo.nickname || '管理员' }}</span>
              <el-icon class="el-icon--right"><ArrowDown /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人信息</el-dropdown-item>
                <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>

      <tags-view v-if="settings.showTagsView" />

      <el-main>
        <router-view v-slot="{ Component }">
          <keep-alive>
            <component :is="Component" />
          </keep-alive>
        </router-view>
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import { ArrowDown, Platform, Brush } from '@element-plus/icons-vue'
import { useUserStore } from '@/store/modules/user'
import { usePermissionStore } from '@/store/modules/permission'
import { themeColors, applyTheme } from '@/assets'
import TagsView from '@/components/TagsView/index.vue'
import settings from '@/config/settings'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const permissionStore = usePermissionStore()

const isCollapse = ref(false)
const menuRoutes = computed(() => permissionStore.menuRoutes)
const activeMenu = computed(() => route.path)

const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value
}

const handleCommand = (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'logout':
      handleLogout()
      break
  }
}

const handleLogout = () => {
  ElMessageBox.confirm(
    '确定要退出登录吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    userStore.logout()
    router.push('/login')
    ElMessage.success('退出成功')
  }).catch(() => {})
}

// 获取当前主题
const currentTheme = computed(() => {
  const savedTheme = localStorage.getItem('theme-color')
  if (savedTheme) {
    try {
      return JSON.parse(savedTheme)
    } catch (e) {
      return themeColors[0]
    }
  }
  return themeColors[0]
})

// 处理主题切换
const handleThemeChange = (theme) => {
  applyTheme(theme)
  ElMessage.success('主题色切换成功')
}

// 初始化主题
onMounted(() => {
  const theme = currentTheme.value
  applyTheme(theme)
})
</script>

<style>
:root {
  --menu-bg-color: #304156;
  --menu-text-color: #bfcbd9;
  --menu-active-text-color: var(--el-color-primary);
}
</style>

<style scoped>
.layout-container {
  height: 100vh;
}

.aside-container {
  background-color: var(--menu-bg-color);
  transition: all 0.3s;
  height: 100%;
  overflow: hidden;
}

.logo-container {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--menu-text-color);
  background-color: var(--menu-bg-color);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  transition: all 0.3s;
}

:deep(.el-menu) {
  border-right: none;
  background-color: var(--menu-bg-color);
}

:deep(.el-menu-item.is-active) {
  background-color: rgba(0, 0, 0, 0.2) !important;
  color: var(--menu-active-text-color) !important;
}

:deep(.el-menu-item:hover),
:deep(.el-sub-menu__title:hover) {
  background-color: rgba(0, 0, 0, 0.1) !important;
}

:deep(.el-sub-menu.is-active .el-sub-menu__title) {
  color: var(--menu-active-text-color) !important;
}

.el-header {
  background-color: #fff;
  border-bottom: 1px solid #e6e6e6;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.theme-picker {
  display: flex;
  align-items: center;
}

.theme-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 5px 0;
}

.theme-color {
  width: 20px;
  height: 20px;
  border-radius: 4px;
}

.user-info {
  display: flex;
  align-items: center;
  padding: 0 8px;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s;
  border: none; /* 默认没有边框 */
}

.user-info:hover {
  background: #f6f6f6;
  border: none; /* 悬停时保证没有边框 */
  outline: none; /* 去掉外部轮廓 */
}
.user-avatar {
  background: var(--el-color-primary);
  color: #fff;
}

.username {
  margin: 0 8px;
  font-size: 14px;
  color: #606266;
}

.el-main {
  padding: 10px;
  background-color: #f0f2f5;
}
</style>
